import cn.le.util.info.HostInfo;
import codec.MessagePachEncoder;
import codec.MessagePackDecoder;
import codec.NettyMessageDecoder;
import codec.NettyMessageEncoder;
import enums.NettyConstant;
import handler.HeartBeatReqHandler;
import handler.LoginAuthReqHandler;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.timeout.ReadTimeoutHandler;
import java.net.InetSocketAddress;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class NettyClient {

  private ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);

  public static void main(String[] args) {
    NettyClient client = new NettyClient();
    client.connect();;
  }

  public void connect(){
    EventLoopGroup group = new NioEventLoopGroup();
    Bootstrap bootstrap = new Bootstrap();
    bootstrap.group(group).channel(NioSocketChannel.class)
        .option(ChannelOption.TCP_NODELAY,true)
        .handler(new ChannelInitializer<SocketChannel>() {
          protected void initChannel(SocketChannel ch) throws Exception {
            //单条最大消息1024*1024
            ch.pipeline().addLast(new NettyMessageDecoder(1024 * 1024,4,4));
            ch.pipeline().addLast(new NettyMessageEncoder());

            //50秒没有读取到消息就关闭当前channel
            //ch.pipeline().addLast("readTimeOutHandler",new ReadTimeoutHandler(50));
            //登录
            ch.pipeline().addLast(new LoginAuthReqHandler());
            //心跳
            ch.pipeline().addLast(new HeartBeatReqHandler());
          }
        });
    try {
      //绑定了本地端口
      /*ChannelFuture future = bootstrap.connect(new InetSocketAddress(NettyConstant.REMOTEIP,NettyConstant.PORT),
          new InetSocketAddress(NettyConstant.LOCALIP,NettyConstant.LOCAL_PORT)).sync();*/
      ChannelFuture future = bootstrap.connect(NettyConstant.REMOTEIP,NettyConstant.PORT).sync();
      future.channel().closeFuture().sync();
    } catch (InterruptedException e) {
      e.printStackTrace();
    }finally {
      //所有资源释放完成之后,清空资源,在此发起重连操作
      /*executor.execute(new Runnable() {
        public void run() {
          try {
            TimeUnit.SECONDS.sleep(5);
            System.out.println("发起重连");
            connect();//发起重连
          }catch (Exception e){
            e.printStackTrace();
          }
        }
      });*/
    }
  }
}
